package com.ithao.controller;

import com.ithao.common.GlobalConst;
import com.ithao.entity.PageResult;
import com.ithao.entity.QueryPageBean;
import com.ithao.entity.Result;
import com.ithao.pojo.User;
import com.ithao.service.UserService;
import com.ithao.vo.LoginParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;


/**
 * @description ：用户控制器
 * @version: 1.0
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 登录接口
     * 根据用户名获取用户对象
     * 判断用户信息是否正确
     * 登录成功，把用户信息存入session对象
     * 返回JSON结果给前端
     */
    @RequestMapping("login")
    public Result login(@RequestBody LoginParam loginParam, HttpServletRequest request) {
        log.info("UserController save...");
        log.debug("loginForm:{}", loginParam);
        User user = userService.findByUsername(loginParam.getUsername());
        if (user == null) {
            return new Result(false, "用户名不正确,或该账号已被禁止");
        }
        BCryptPasswordEncoder bCrypt = new BCryptPasswordEncoder();
        if (bCrypt.matches(loginParam.password,user.getPassword())) {
            // 把用户对象放入session中
            request.getSession(true).setAttribute(GlobalConst.SESSION_KEY_USER, user);
            return new Result(true, "登录成功");
        } else {
            return new Result(false, "密码错误");
        }
    }

    /**
     * 退出登录
     */
    @RequestMapping("logout")
    public Result logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.info("[登出]……");
        //从session中删除用户
        request.getSession().removeAttribute(GlobalConst.SESSION_KEY_USER);
        //重定向到登录页
        response.sendRedirect(request.getContextPath() + "/login.html");
        return null;
    }

    @PostMapping("/findPage")
    public Result findPage(@RequestBody QueryPageBean queryPageBean) {
        if (queryPageBean == null) {
            queryPageBean = new QueryPageBean();
            queryPageBean.setCurrentPage(1);
            queryPageBean.setPageSize(10);
        }
        log.info("用户分页查找 queryPageBean:{}",queryPageBean);
        PageResult pageResult = userService.findPage(queryPageBean);
        return new Result(true,"查找成功",pageResult);
    }

    /**
     * 启用禁用
     */
    @PostMapping("/updateState")
    public Result updateState(@RequestBody Map map) {
        if (map == null || map.size() == 0) {
            throw new RuntimeException("参数为空");
        }
        Integer id = (Integer) map.get("id");
        Integer state = (Integer) map.get("state");
        log.info("[用户的禁用启用 ] userId:{}   status:{}", id, state);
        if (state == 0) {
            userService.updateStatus(id, 1);
            return new Result(true, "用户启动成功");
        } else  {
            userService.updateStatus(id, 0);
            return new Result(true, "用户禁用成功");
        }
    }

    /**
     * 新增用户
     */
    @PostMapping("/add")
    public Result add(@RequestBody User user,Integer[] RoleIds) {
        log.info("[用户新增]User:{},  RoleIds:{}",user,RoleIds);
        //密码加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userService.add(user,RoleIds);
        return new Result(true,"新增用户成功");
    }

    @PostMapping("/delete")
    public Result delete(@RequestParam("id") Integer id) {
        log.info("[删除用户] userId:{}",id);
        userService.delete(id);
        return new Result(true,"删除成功");
    }

    @RequestMapping("/findById")
    public Result findById(@RequestParam("id") Integer id) {
        log.info("[查找用户] userId:{}",id);
        User user = userService.findById(id);
        return new Result(true,"查找成功",user);
    }

    /**
     * 查找用户选中的角色的Id
     * @param userId
     * @return
     */
    @GetMapping("/findRolesById")
    public Result findRolseById(@RequestParam("userId") Integer userId) {
        List<Integer> roleIds = userService.findRolesById(userId);
        return new Result(true, "查找成功", roleIds);
    }
    @PostMapping("/update")
    public Result update(@RequestBody User user,Integer[] RoleIds) {
        log.info("[更新用户] user:{}RoleIds:{}",user,RoleIds);
        userService.update(user,RoleIds);
        return new Result(true,"更新成功");
    }
}
